package com.ray.finance.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.ray.base.builder.MaterialTypeBuilder;
import com.ray.base.check.MaterialTypeCheck;
import com.ray.base.service.BaseCustomerService;
import com.ray.base.table.entity.BaseCustomer;
import com.ray.base.table.entity.BaseMaterialType;
import com.ray.base.table.params.material.type.MaterialTypeCreateParams;
import com.ray.common.check.AbstractCheck;
import com.ray.finance.builder.BillAdjustBuilder;
import com.ray.finance.check.BillCheck;
import com.ray.finance.service.FinaBillAdjustService;
import com.ray.finance.service.FinaBillService;
import com.ray.finance.table.dto.BillAdjuestQueryDTO;
import com.ray.finance.table.dto.BillAmountChangeDTO;
import com.ray.finance.table.entity.FinaBill;
import com.ray.finance.table.entity.FinaBillAdjust;
import com.ray.finance.table.params.BillAdjuestQueryParams;
import com.ray.finance.table.params.BillAdjustCreateParams;
import com.ray.finance.table.vo.BillAdjustVO;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.enums.YesOrNoEnum;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 对账单
 * @Class: BillApi
 * @Package com.ray.finance.api
 * @date 2020/6/15 15:35
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
@Service
public class BillAdjustApi {

   @Autowired
    private FinaBillAdjustService finaBillAdjustService;
    @Autowired
    private BaseCustomerService baseCustomerService;
    @Autowired
    private FinaBillService finaBillService;

    /**
     * 查询物料列表信息--启用的物料
     *
     * @param queryParams
     * @return
     */
    public Result<List<BillAdjustVO>> queryAdjusts(BillAdjuestQueryParams queryParams) {
        Assert.notNull(queryParams, "参数[queryParams]不存在");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        Map<String, BaseCustomer> baseCustomerMap = new HashMap<>();
        BillAdjuestQueryDTO queryDTO = new BillAdjuestQueryDTO();
        BeanUtil.copyProperties(queryParams, queryDTO);
        queryDTO.setStatus(YesOrNoEnum.YES.getValue());
        List<FinaBillAdjust> finaBillAdjusts = finaBillAdjustService.list(queryDTO, loginUser);
        //查询对象
        List<BillAdjustVO> list = new ArrayList<>();
        if (ObjectUtil.isNotNull(finaBillAdjusts)) {
            list = finaBillAdjusts.stream().map(adjust -> {
                BillAdjustVO adjustVO = new BillAdjustVO();
                BeanUtil.copyProperties(adjust, adjustVO);
                //查询客信息
                BaseCustomer baseCustomer = baseCustomerMap.get(adjust.getCustomerCode());
                if (ObjectUtil.isEmpty(baseCustomer)) {
                    baseCustomer = baseCustomerService.queryCustomerByCustomerCode(adjust.getCustomerCode(), loginUser);
                    baseCustomerMap.put(adjust.getCustomerCode(), baseCustomer);
                }
                adjustVO.setCustomerName(baseCustomer.getCustomerName());
                return adjustVO;
            }).collect(Collectors.toList());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, list);
    }


    /**
     * 创建产品类型
     *
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createAdjust(BillAdjustCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        FinaBill finaBill = finaBillService.queryBillByBillNo(createParams.getBillNo(),loginUser);
        new BillCheck(finaBill).checkNull("对账单不存在").checkAdjust("对账单不能调整");
        BillAdjustBuilder billAdjustBuilder = new BillAdjustBuilder();
        billAdjustBuilder.append(createParams).append(finaBill).appendCreate(loginUser);
        //保存产品类型信息
        if (!finaBillAdjustService.save(billAdjustBuilder.bulid())) {
            log.info("保存調整但接口异常,参数:{}", JSON.toJSONString(billAdjustBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        BillAmountChangeDTO billAmountChangeDTO = new BillAmountChangeDTO(finaBill.getBillNo(),finaBill.getAmount().add(createParams.getAmount()),finaBill.getUpdateVersion());
        if(!finaBillService.updateAmount(billAmountChangeDTO,loginUser)){
            throw  BusinessExceptionFactory.newException("更新对账单金额");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, billAdjustBuilder.getCode());
    }


    @Transactional
    public Result<String> deleteAdjust(String adjustCode) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        FinaBillAdjust finaBillAdjust = finaBillAdjustService.queryAdjustByNo(adjustCode,loginUser);
        new AbstractCheck<>(finaBillAdjust).checkNull("调整单不存在");
        BillAdjustBuilder billAdjustBuilder = new BillAdjustBuilder();
        billAdjustBuilder.appendCode(adjustCode).delete().appendEdit(loginUser);
        //保存产品类型信息
        if (!finaBillAdjustService.edit(billAdjustBuilder.bulid(),loginUser)) {
            log.info("保存調整但接口异常,参数:{}", JSON.toJSONString(billAdjustBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        //查询调整单
        FinaBill finaBill = finaBillService.queryBillByBillNo(finaBillAdjust.getBillNo(),loginUser);
        new BillCheck(finaBill).checkNull("对账单不存在");
        BillAmountChangeDTO billAmountChangeDTO = new BillAmountChangeDTO(finaBill.getBillNo(),finaBill.getAmount().subtract(finaBillAdjust.getAmount()),finaBill.getUpdateVersion());
       if(!finaBillService.updateAmount(billAmountChangeDTO,loginUser)){
           throw  BusinessExceptionFactory.newException("更新对账单金额");
       }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, billAdjustBuilder.getCode());
    }


}
